package cn.leonis.leetcode;

/**
 * @author Tobi
 * @time 2021-10-02 8:18 PM
 * 将一个数字转换为16进制
 */
public class Covert2HexSolution {

    public static void main(String[] args) {
        int num = 16;
        Covert2HexSolution solution = new Covert2HexSolution();
        System.out.println(solution.toHex(num));
    }

    public String toHex(int num) {
        if (num == 0) {
            return "0";
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 7; i >= 0; i--) {
            int value = (num >> (4 * i)) & 0xf;
            if (sb.length() > 0 || value > 0) {
                char c = value < 10 ? (char) ('0' + value) : (char) ('a' + value - 10);
                sb.append(c);
            }
        }
        return sb.toString();
    }
}
